(function($){
	var KEY = "jforest.upload";

	var Upload = function(element,options){
		this.$el = $(element);
		var self = this;
		this.options = $.extend({
			callback:function(result){
				self.$el.val(result.data);
			}
		},options);
		this._initial();
	};

	Upload.prototype = {
		_initial:function(){
			var targetName = '_ajax_upload_target' + jf.getId();
			this.iframeTarget = $('<iframe name="'+targetName+'" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" style="display:none;"></iframe>');
			this.formArea = $('<div style="display:none;"><form method="post" enctype="multipart/form-data" target="'+targetName+'" action="' + this.options.url + '"><input type="file"/></form></div>');
			var self = this;
			this.fileInput = this.formArea.find('input[type="file"]').change(function(){
				self.formArea.find('form').submit();
			});
			
			this.iframeTarget.bind('load', function() {
				var doc = self._iframeDoc(self.iframeTarget);
				var pre = doc.getElementsByTagName('pre')[0];
				var str = '';
				if(pre){
					str = pre.innerHTML;
				}else{
					str = doc.body.innerHTML;
				}
				try {
					var result = $.parseJSON(str);
					self.options.callback.apply(self,[result]);
				} catch (e) {}
			});
			$('body').append(this.iframeTarget);
			$('body').append(this.formArea);
		},
		_iframeDoc:function(iframe) {
			return iframe[0].contentDocument || iframe[0].contentWindow.document;
		},
		upload:function(){
			this.formArea.find('input[type="file"]').click();
		}
	};
	
	$.fn.jfUpload = function(){
		var args = Array.prototype.slice.call(arguments, 0);
		var value = undefined;
		this.each(function () {
			var $this = $(this);
			if (args.length === 0 || typeof(args[0]) === "object") {
				opts = args.length === 0 ? {} : $.extend({}, args[0]);
				$this.data(KEY,new Upload(this,opts)); //创建控件
			}else if (typeof(args[0]) === "string"){
				var entity = $this.data(KEY);
                if(entity === undefined){return;}
                value = entity[args[0]].apply(entity, args.slice(1));
			}else{
				 throw 'Invalid arguments to '+KEY+' plugin: ' + args;
			}
	    });
	    return (value === undefined) ? this : value;
	};
	
	$.fn.jfUpload.Constructor = Upload;
	
})(window.jQuery)